package pers.goetboy.common.utils;

import pers.goetboy.common.exception.BaseCommonException;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.TemporalAccessor;
import java.util.Arrays;
import java.util.List;

/**
 * @author goetb
 */
public class LocalDateTimeUtils {
    private static final List<DateTimeFormatter> DATE_TIME_FORGATHERS = Arrays.asList(
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSS"),
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"),
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"),
            DateTimeFormatter.ISO_LOCAL_DATE_TIME
            );
    private static final List<DateTimeFormatter> TIME_FORGATHERS = Arrays.asList(
            DateTimeFormatter.ISO_LOCAL_TIME, DateTimeFormatter.ofPattern("HH:mm:ss"),
            DateTimeFormatter.ofPattern("HH:mm:ss.SSS"),
            DateTimeFormatter.ofPattern("HH:mm:ss.SSSS"));

    /**
     * 判断日期字符串的格式
     *
     * @param date
     * @return
     */
    public static LocalDateTime parse(String date) {

        for (DateTimeFormatter dateTimeForgather : DATE_TIME_FORGATHERS) {
            try {
                TemporalAccessor temporalAccessor = dateTimeForgather.parse(date);
                return LocalDateTime.from(temporalAccessor);
            } catch (DateTimeParseException e) {
                continue;
            }


        }
        throw new BaseCommonException("没有找到可用的日期转换工具,请核对日期格式是否正确:" + date);
    }


    public static LocalDate parseDate(String date) {
        return null;
    }

    public static LocalTime parseTime(String date) {
        for (DateTimeFormatter timeForgather : TIME_FORGATHERS) {
            try {
                TemporalAccessor temporalAccessor = timeForgather.parse(date);
                return LocalTime.from(temporalAccessor);
            } catch (DateTimeParseException e) {
                //无法转换就使用下一个转换器
                continue;
            }
        }
        throw new BaseCommonException("没有找到可用的日期转换工具,请核对时间格式是否正确:" + date);
    }

    public static void main(String[] args) {
        System.out.println(parse("2019-01-12 12:12:12"));
        System.out.println(parse("2019-01-12 12:12:12.335"));
        System.out.println(parse("2019-01-12 12:12:12.2221"));

        System.out.println(parseTime("12:12:12"));
        System.out.println(parseTime("12:12:12.335"));
        System.out.println(parseTime("12:12:12.2221"));
    }
}
